$: << File.join(File.expand_path(File.dirname(__FILE__)), "..")
#===============================
# Return uniq keys
#==============================
require 'rubygems'
require 'optparse'
require 'EasyHadoop'

class Uniq < EasyHadoop
	
	@@RETAIN_OPERATIONS = ["first","last","all"]
	attr_reader :key, :values

	def initialize(arguments)
		super(arguments)
		@key = nil
		@values = []		
	end
	
	def set_mandatory
		super
		@mandatory << :retain
	end
	
	def set_commands
		super
		@options[:retain]=false
		@optparse.on('--retain ARGUMENT', "By default, this class only returns 
		uniq key values. However it is possible to return values by setting retain option to #{@@RETAIN_OPERATIONS.join(', ')}"){|opt|
		 
			raise OptionParser::InvalidArgument, "Invalid retain argument. 
			Expecting one of the following: #{@@RETAIN_OPERATIONS.join(', ')}" unless (
				@@RETAIN_OPERATIONS.include?(opt.strip().downcase)
			)
		
			@options[:retain]=opt
		}
	end
	
	
	def print(line)
		return nil if @key.nil?
		output = ""
		if(!@options[:retain])
			output = "#{@key}"
		elsif(@options[:retain]=="all")
			@values.each_index{|index| @values[index]=@values.join("|")}
			grp = @values.join("\t")
			output = "#{@key}\t#{grp}"
		elsif @options[:retain] == "first"
			output = ([key] + @values.first).join(@options[:output_delimiter])
		elsif (@options[:retain] == "last")
			output = ([key] + @values.last).join(@options[:output_delimiter])
		end
		@values.clear
		@key = nil
		return output
	end
	
	def execute(line)
		return nil if line == nil or line.to_s.strip().length == 0
		value = line.chomp.split(@options[:input_delimiter])
		key = value.shift

		#Sanity Checks
		return if key == nil or key.to_s.strip().length == 0
		key = key.to_s.strip()
		if(key != @key)
			yield print(line)
			@key = key
		end
		
		if(value and value.kind_of?(Array))
			@values << value
		else
			@values << [value]
		end
		
	end
end

# Scripting Option
if __FILE__ == $0
    cls = Uniq.new(ARGV)
    STDIN.each_line{|line|
	  cls.execute(line) {|value| puts value unless value.nil? }
    }
end


